'use strict'
const crypto = require('crypto');
const nunjucks = require('nunjucks');

// this 是 helper 对象，在其中可以调用其他 helper 方法
// this.ctx => context 对象
// this.app => application 对象
module.exports = {

    res(message = '', code = 200, data = ''){
        return {
            code,
            message,
            data
        };
    },
    test(){
        return "test";
    },
    renderString(str, data){
        return nunjucks.renderString(str, data);
    },

    /**
     * oss 上传签名
     * @param accesskey oos加密的key
     * @param expire  过期时间 默认10分钟
     * @param maxSize 上传大小 默认10M = 1024 * 1204 * 10
     * @param dir 指定用户上传的文件目录 必须在此目录下才能上传
     * @returns {*}
     */
    oosSign(secret, expire = 10, maxSize = 1048576000, dir = '') {

        let date = new Date();
        let timestamp = date.getTime() + expire * 60 * 1000;
        let expiration = new Date(timestamp).toISOString();

        dir = dir == '' ? date.getTime() : dir;

        let policyText = {
            "expiration": expiration, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
            "conditions": [
                ["content-length-range", 0, maxSize], // 设置上传文件的大小限制 默认10M = 1024 * 1014 * 10
                ["starts-with","$key",`temp/${dir}/`] //指定上传到的目录前缀
            ]
        };

        let base64Policy = new Buffer(JSON.stringify(policyText)).toString("base64");

        //signature
        let hmac = crypto.createHmac('sha1', secret);
        hmac.update(base64Policy);
        let signature = hmac.digest('base64');

        let result = {
            policy: base64Policy,
            signature: signature,
            expire: timestamp,
            maxSize,
            dir: `temp/${dir}/`
        }

        return result;
    },
};